package com.joinway.framework.support.audit;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class RequestHeaderAspect {
	
	private final static Logger log = LoggerFactory.getLogger(RequestHeaderAspect.class);
	
	protected RequestHeaderAuditor auditor;
	
	public Object doAround(ProceedingJoinPoint point) throws Throwable {
		
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		Enumeration<String> names = request.getHeaderNames();
		Map<String, String> headers = new HashMap<>();
		
		if(names != null){
			while(names.hasMoreElements()){
				String name = names.nextElement();
				String value = request.getHeader(name);
				headers.put(name, value);
			}
		}
		
		Object value = null;
		
		try{
			value = point.proceed(point.getArgs());
			auditor.audit(headers, value, point.getArgs());
		}catch(Throwable t){
			throw t;
		}
		
		return value;
	}

	public RequestHeaderAuditor getAuditor() {
		return auditor;
	}

	public void setAuditor(RequestHeaderAuditor auditor) {
		this.auditor = auditor;
	}
}
